<template>
  <div class="app">
    <h2>共享可组合项 + stop 演示</h2>
    <p>全局鼠标位置：{{ x }}, {{ y }}</p>

    <button @click="showA = !showA">
      {{ showA ? "卸载组件 A" : "挂载组件 A" }}
    </button>
    <button @click="showB = !showB">
      {{ showB ? "卸载组件 B" : "挂载组件 B" }}
    </button>

    <div class="components">
      <MouseA v-if="showA" />
      <MouseB v-if="showB" />
    </div>
  </div>
</template>

<script setup>
import { ref, effectScope, onScopeDispose, defineComponent, h } from "vue";

/* --------------------------
 * 原始 useMouse
 * -------------------------- */
function useMouse() {
  const x = ref(0);
  const y = ref(0);

  function handler(e) {
    x.value = e.x;
    y.value = e.y;
  }

  window.addEventListener("mousemove", handler);

  onScopeDispose(() => {
    console.log("❌ 移除 mousemove 监听");
    window.removeEventListener("mousemove", handler);
  });

  return { x, y };
}

/* --------------------------
 * createSharedComposable
 * -------------------------- */
function createSharedComposable(composable) {
  let subscribers = 0;
  let state, scope;

  const dispose = () => {
    if (scope && --subscribers <= 0) {
      console.log("🧹 effectScope stop 被调用");
      scope.stop();
      scope = state = null;
    } else {
      console.log("🔹 有组件仍在使用，subscribers =", subscribers);
    }
  };

  return (...args) => {
    subscribers++;
    if (!state) {
      console.log("🟢 创建共享 scope");
      scope = effectScope(true);
      state = scope.run(() => composable(...args));
    }
    onScopeDispose(dispose);
    return state;
  };
}

/* --------------------------
 * 共享 useMouse
 * -------------------------- */
const useSharedMouse = createSharedComposable(useMouse);
const { x, y } = useSharedMouse();

/* --------------------------
 * 动态挂载/卸载的子组件
 * -------------------------- */
const MouseA = defineComponent({
  name: "MouseA",
  setup() {
    const { x, y } = useSharedMouse();
    return () =>
      h("div", { class: "child" }, [
        h("h3", "组件 A"),
        h("p", `x: ${x.value}, y: ${y.value}`),
      ]);
  },
});

const MouseB = defineComponent({
  name: "MouseB",
  setup() {
    const { x, y } = useSharedMouse();
    return () =>
      h("div", { class: "child" }, [
        h("h3", "组件 B"),
        h("p", `x: ${x.value}, y: ${y.value}`),
      ]);
  },
});

/* 控制子组件显示 */
const showA = ref(true);
const showB = ref(true);
</script>

<style scoped>
.app {
  padding: 20px;
  font-family: sans-serif;
}
.components {
  display: flex;
  gap: 40px;
  margin-top: 20px;
}
.child {
  padding: 12px;
  border: 1px solid #aaa;
  border-radius: 8px;
  width: 200px;
}
button {
  margin-right: 10px;
  margin-top: 10px;
}
</style>
